package com.xinsoft.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinsoft.common.ApplicationContextRegister;
import com.xinsoft.common.Response;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.*;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.*;
import com.xinsoft.service.*;
import com.xinsoft.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * k8业务单据同步
 */
@Slf4j
@Service
public class SyncPullBillKisServiceImpl implements SyncPullBillService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysSupplierService sysSupplierService;
    @Autowired
    private MesBomService mesBomService;
    @Autowired
    private SysMaterialService sysMaterialService;
    @Resource
    private RedisUtil redisUtil;
    private String time = "2023-11-01";

    /**
     * 生产计划
     * @return
     */
    @Override
    public List<MesProducePlan> productionSync() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("PageSize", "250");
        paramMap.put("Filter", " and t1.FConfirmDate>='2023-11-01'");
        paramMap.put("ItemClassId", "85");
        paramMap.put("PageNo", "1");
        paramMap.put("Acct", "XRTEST");
        paramMap.put("QueryFields", "FItemId,FName,FNumber,FHelpCode,FModel,FAuxClassID,FAuxClassID_FName,FErpClsID_FName,FErpClsID,FTypeID,FTypeID_FName,FUnitID,FUnitID_FName,FSecInv,FUseState,FUseState_FName,FSecUnitID_FName,FSecUnitID,FSecCoefficient,FDefaultLoc,FDefaultLoc_FName,FSPID_FFullName,FSPID,FLowLimit,FHighLimit");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisProductionPlanDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisProductionPlanDto.class)).collect(Collectors.toList());
        List<MesProducePlan> productionPlanVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());


        //获取销售订单数据
        List<Integer> sourceIds = productionPlanVOS.stream().map(MesProducePlan::getSourceId).collect(Collectors.toList());
        ErpSalePageParam saleParam = new ErpSalePageParam();
        saleParam.setSourceIds(sourceIds);
        List<ErpSaleVO> erpSaleVOS = this.saleSync(saleParam);
        Map<Integer, ErpSaleVO> saleVOMap = erpSaleVOS.stream().collect(Collectors.toMap(item -> item.getId(), item -> item, (v1, v2) -> v1));

        List<Integer> materialIds = productionPlanVOS.stream().map(MesProducePlan::getMaterialId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            productionPlanVOS.forEach(item-> {
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setAssistUom(sysMaterial.getViceUnit());
                    item.setConvCoefficient(ObjectUtil.isEmpty(sysMaterial.getConvCoefficient()) ? BigDecimal.ZERO : new BigDecimal(sysMaterial.getConvCoefficient()));
                    item.setAssistNum((ObjectUtil.isEmpty(item.getPlanNum()) || item.getPlanNum().equals(BigDecimal.ZERO) || ObjectUtil.isEmpty(item.getConvCoefficient())) ?
                            BigDecimal.ZERO : item.getPlanNum().multiply(item.getConvCoefficient()));
                }
                if(saleVOMap.containsKey(item.getSourceId())) {
                    ErpSaleVO saleVO = saleVOMap.get(item.getSourceId());
                    item.setSourceCode(saleVO.getCode());
                }
            });
        }
        return productionPlanVOS;
    }
    /**
     * 生产计划
     * @return
     */
    @Override
    public List<MesProducePlan> productionSyncTwoYears(Date startTime, Date endTime) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("PageSize", "250");
        paramMap.put("Filter", " and t1.FConfirmDate>= '" + DateUtil.format(startTime,"yyyy-MM-dd")
                + "' and t1.FConfirmDate < '" + DateUtil.format(endTime,"yyyy-MM-dd") + "'" );
        log.error("========================filter:{}",paramMap.get("Filter"));
        paramMap.put("ItemClassId", "85");
        paramMap.put("PageNo", "1");
        paramMap.put("Acct", "XRTEST");
        paramMap.put("QueryFields", "FItemId,FName,FNumber,FHelpCode,FModel,FAuxClassID,FAuxClassID_FName,FErpClsID_FName,FErpClsID,FTypeID,FTypeID_FName,FUnitID,FUnitID_FName,FSecInv,FUseState,FUseState_FName,FSecUnitID_FName,FSecUnitID,FSecCoefficient,FDefaultLoc,FDefaultLoc_FName,FSPID_FFullName,FSPID,FLowLimit,FHighLimit");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisProductionPlanDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisProductionPlanDto.class)).collect(Collectors.toList());
        List<MesProducePlan> productionPlanVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());

        List<Integer> materialIds = productionPlanVOS.stream().map(MesProducePlan::getMaterialId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            productionPlanVOS.forEach(item-> {
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setAssistUom(sysMaterial.getViceUnit());
                    item.setConvCoefficient(ObjectUtil.isEmpty(sysMaterial.getConvCoefficient()) ? BigDecimal.ZERO : new BigDecimal(sysMaterial.getConvCoefficient()));
                    item.setAssistNum((ObjectUtil.isEmpty(item.getPlanNum()) || item.getPlanNum().equals(BigDecimal.ZERO) || ObjectUtil.isEmpty(item.getConvCoefficient())) ?
                            BigDecimal.ZERO : item.getPlanNum().multiply(item.getConvCoefficient()));
                }
            });
        }
        return productionPlanVOS;
    }


    /**
     * 生产投料
     * @return
     */
    @Override
    public List<ErpProductionFeedingVO> feedingSync(MesFeedingPlanPageParam mesFeedingPlanPageParam) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", " and t1.FCheckDate>='2023-11-01'");
        paramMap.put("ItemClassId", "88");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisProductionFeedingDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisProductionFeedingDto.class)).collect(Collectors.toList());
        List<ErpProductionFeedingVO> productionFeedingVOS = headVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpProductionFeedingVO::getId).reversed()).collect(Collectors.toList());
        List<Integer> materialIds = productionFeedingVOS.stream().map(ErpProductionFeedingVO::getMaterialId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            productionFeedingVOS.forEach(item-> {
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMaterialName(sysMaterial.getMaterialName());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                    item.setMainUnit(sysMaterial.getMainUnitKis());
                    item.setViceUnit(sysMaterial.getViceUnitKis());
                    item.setAssistNum((ObjectUtil.isEmpty(item.getPlanCount()) || item.getPlanCount().equals(BigDecimal.ZERO) || ObjectUtil.isEmpty(item.getConvCoefficient())) ?
                            BigDecimal.ZERO : item.getPlanCount().multiply(item.getConvCoefficient()));

                }
                if(materialMap.containsKey(item.getMaterialId())) item.setMaterialName(materialMap.get(item.getMaterialId()).getMaterialName());
            });
        }
        return productionFeedingVOS;
    }

    /**
     * 生产投料
     * @return
     */
    @Override
    public List<ErpProductionFeedingDetailVO> feedingDetailSync(List<Integer> ids) {
        String idsParam = StringUtils.join(ids, ",");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", " and t1.FCheckDate>='2023-11-01'" + " and  t1.FInterID in (" + idsParam + ")");
        paramMap.put("ItemClassId", "88");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisProductionFeedingDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisProductionFeedingDto.class)).collect(Collectors.toList());
        List<ErpProductionFeedingVO> productionFeedingVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        List<KisProductionFeedingDetailDto> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisProductionFeedingDetailDto.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpProductionFeedingDetailVO> sourcingItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpProductionFeedingDetailVO::getHeadId).reversed()).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(sourcingItemVOS) || ObjectUtil.isEmpty(productionFeedingVOS)){
            return null;
        }
        ErpProductionFeedingVO feedingVO = productionFeedingVOS.get(0);
        List<Integer> materialIds = sourcingItemVOS.stream().map(ErpProductionFeedingDetailVO::getMaterialId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingItemVOS.forEach(item-> {
                item.setCreateTime(feedingVO.getCreateTime());
                item.setHeadCode(feedingVO.getFeedingNo());
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMaterialName(sysMaterial.getMaterialName());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                    item.setMainUnitName(sysMaterial.getMainUnitKis());
                }
            });
        }
        return sourcingItemVOS;
    }

    @Override
    public List<ErpFeedingOutVO> feedingOutSync(ErpFeedingOutPageParam param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", " and t1.FCheckDate>='2023-11-01'");
        paramMap.put("ItemClassId", "24");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisFeedingOutDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisFeedingOutDto.class)).collect(Collectors.toList());
        List<ErpFeedingOutVO> feedingOutVOS = headVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpFeedingOutVO::getId).reversed()).collect(Collectors.toList());

        if (ObjectUtil.isEmpty(feedingOutVOS) || ObjectUtil.isEmpty(feedingOutVOS)){
            return null;
        }
        List<Integer> userIds = feedingOutVOS.stream().map(ErpFeedingOutVO::getCheckerId).collect(Collectors.toList());
        List<Integer> billerIds = feedingOutVOS.stream().map(ErpFeedingOutVO::getBillerId).collect(Collectors.toList());
        List<Integer> sManagerIds = feedingOutVOS.stream().map(ErpFeedingOutVO::getSManagerId).collect(Collectors.toList());
        List<Integer> fManagerIds = feedingOutVOS.stream().map(ErpFeedingOutVO::getFManagerId).collect(Collectors.toList());
        userIds.addAll(billerIds);
        userIds.addAll(sManagerIds);
        userIds.addAll(fManagerIds);
        if (ObjectUtil.isNotEmpty(userIds)){
            List<SysUser> sysUserDOS = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userIds).or().in(SysUser::getClerkId, userIds));
            Map<Integer, SysUser> sysUserMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            Map<Integer, SysUser> sysClerkMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getClerkId(), Iterable -> Iterable, (v1, v2) -> v1));
            feedingOutVOS.forEach(item-> {
                if(sysClerkMap.containsKey(item.getCheckerId())) item.setCheckerName(sysClerkMap.get(item.getCheckerId()).getRealName());
                if(sysClerkMap.containsKey(item.getBillerId())) item.setBillerName(sysClerkMap.get(item.getBillerId()).getRealName());
                if(sysUserMap.containsKey(item.getSManagerId())) item.setSManagerName(sysUserMap.get(item.getSManagerId()).getRealName());
                if(sysUserMap.containsKey(item.getFManagerId())) item.setFManagerName(sysUserMap.get(item.getFManagerId()).getRealName());
            });
        }
        return feedingOutVOS;
    }
    @Override
    public List<ErpFeedingOutDetailVO> feedingOutDetailSync(List<Integer> ids) { HashMap<String, Object> paramMap = new HashMap<>();
        String idsParam = StringUtils.join(ids, ",");
        paramMap.put("Filter", " and t1.FInterID in (" + idsParam + ")");
        paramMap.put("ItemClassId", "24");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisFeedingOutDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisFeedingOutDto.class)).collect(Collectors.toList());
        List<ErpFeedingOutVO> feedingOutVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        List<KisFeedingOutBodyVO> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisFeedingOutBodyVO.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpFeedingOutDetailVO> sourcingItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpFeedingOutDetailVO::getHeadId).reversed()).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(feedingOutVOS) || ObjectUtil.isEmpty(feedingOutVOS)){
            return null;
        }
        List<Integer> userIds = feedingOutVOS.stream().map(ErpFeedingOutVO::getCheckerId).collect(Collectors.toList());
        List<Integer> billerIds = feedingOutVOS.stream().map(ErpFeedingOutVO::getBillerId).collect(Collectors.toList());
        List<Integer> sManagerIds = feedingOutVOS.stream().map(ErpFeedingOutVO::getSManagerId).collect(Collectors.toList());
        List<Integer> fManagerIds = feedingOutVOS.stream().map(ErpFeedingOutVO::getFManagerId).collect(Collectors.toList());
        userIds.addAll(billerIds);
        userIds.addAll(sManagerIds);
        userIds.addAll(fManagerIds);
        if (ObjectUtil.isNotEmpty(userIds)){
            List<SysUser> sysUserDOS = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userIds).or().in(SysUser::getClerkId, userIds));
            Map<Integer, SysUser> sysUserMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            Map<Integer, SysUser> sysClerkMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getClerkId(), Iterable -> Iterable, (v1, v2) -> v1));
            feedingOutVOS.forEach(item-> {
                if(sysClerkMap.containsKey(item.getCheckerId())) item.setCheckerName(sysClerkMap.get(item.getCheckerId()).getRealName());
                if(sysClerkMap.containsKey(item.getBillerId())) item.setBillerName(sysClerkMap.get(item.getBillerId()).getRealName());
                if(sysUserMap.containsKey(item.getSManagerId())) item.setSManagerName(sysUserMap.get(item.getSManagerId()).getRealName());
                if(sysUserMap.containsKey(item.getFManagerId())) item.setFManagerName(sysUserMap.get(item.getFManagerId()).getRealName());
            });
        }
        ErpFeedingOutVO feedingOutVO = feedingOutVOS.get(0);
        List<Integer> materialIds = sourcingItemVOS.stream().map(ErpFeedingOutDetailVO::getMaterialId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingItemVOS.forEach(item-> {
                item.setHeadCode(feedingOutVO.getCode());
                item.setCheckDate(feedingOutVO.getCheckDate());
                item.setBillerName(feedingOutVO.getBillerName());
                SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                if(ObjectUtil.isNotEmpty(sysMaterial)) {
                    item.setMaterialName(materialMap.get(item.getMaterialId()).getMaterialName());
                    item.setMainUnitName(materialMap.get(item.getMaterialId()).getMainUnitKis());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                }
            });
        }
        return sourcingItemVOS;
    }

    /**
     * 委外订单
     * @return
     */
    @Override
    public List<ErpOutSourcingVO> sourcing(ErpSourcingPageParam param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", "  and t1.FCheckDate >= '2023-11-01' ");
        paramMap.put("ItemClassId", "1007105");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisOutSourcingHeadVO> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisOutSourcingHeadVO.class)).collect(Collectors.toList());
        List<ErpOutSourcingVO> sourcingVOS = headVOS.stream().map(item -> item.voToPo(item)).sorted(Comparator.comparing(ErpOutSourcingVO::getId).reversed()).collect(Collectors.toList());
        List<Integer> supplyIds = sourcingVOS.stream().map(ErpOutSourcingVO::getSupplyID).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplierDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplierMap = supplierDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingVOS.forEach(item-> {
                if(supplierMap.containsKey(item.getSupplyID())) item.setSupplyName(supplierMap.get(item.getSupplyID()).getSupplierName());
            });
        }
        List<Integer> userIds = sourcingVOS.stream().map(ErpOutSourcingVO::getCreateId).collect(Collectors.toList());
        List<Integer> auditorIds = sourcingVOS.stream().map(ErpOutSourcingVO::getAuditorId).collect(Collectors.toList());
        userIds.addAll(auditorIds);
        if (ObjectUtil.isNotEmpty(userIds)){
            List<SysUser> sysUserDOS = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userIds).or().in(SysUser::getClerkId, userIds));
            Map<Integer, SysUser> sysUserMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            Map<Integer, SysUser> sysClerkMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getClerkId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingVOS.forEach(item-> {
                if(sysUserMap.containsKey(item.getCreateId())) item.setCreateName(sysUserMap.get(item.getCreateId()).getRealName());
                if(sysClerkMap.containsKey(item.getAuditorId())) item.setAuditorName(sysClerkMap.get(item.getAuditorId()).getRealName());
            });
        }
        return sourcingVOS;
    }

    /**
     * 委外订单详情
     * @return
     */
    @Override
    public List<ErpOutSourcingItemVO> sourcingItem(List<Integer> ids) {
        HashMap<String, Object> paramMap = new HashMap<>();
        String idsParam = StringUtils.join(ids, ",");
        paramMap.put("Filter", " and t1.FInterID in (" + idsParam + ")");
        paramMap.put("ItemClassId", "1007105");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisOutSourcingHeadVO> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisOutSourcingHeadVO.class)).collect(Collectors.toList());
        List<ErpOutSourcingVO> sourcingVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        List<KisOutSourcingBodyVO> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisOutSourcingBodyVO.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpOutSourcingItemVO> sourcingItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpOutSourcingItemVO::getHeadId).reversed()).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(sourcingVOS) || ObjectUtil.isEmpty(sourcingVOS)){
            return null;
        }
        List<Integer> bomIds = sourcingItemVOS.stream().map(ErpOutSourcingItemVO::getBomID).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(bomIds)){
            List<MesBom> bomDOS = mesBomService.list(new LambdaQueryWrapper<MesBom>().in(MesBom::getId, bomIds));
            Map<Integer, MesBom> bomMap = bomDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingItemVOS.forEach(item-> {
                if(bomMap.containsKey(item.getBomID())) item.setBomName(bomMap.get(item.getBomID()).getBomName());
            });
        }
        List<Integer> supplyIds = sourcingVOS.stream().map(ErpOutSourcingVO::getSupplyID).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplierDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplierMap = supplierDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingVOS.forEach(item-> {
                if(supplierMap.containsKey(item.getSupplyID())) item.setSupplyName(supplierMap.get(item.getSupplyID()).getSupplierName());
            });
        }
        Map<Integer, ErpOutSourcingVO> sourcingVOMap = sourcingVOS.stream().collect(Collectors.toMap(item -> item.getId(), item -> item, (v1, v2) -> v1));
        List<Integer> materialIds = sourcingItemVOS.stream().map(ErpOutSourcingItemVO::getMaterialId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingItemVOS.forEach(item-> {
                ErpOutSourcingVO sourcingVO = sourcingVOMap.get(item.getHeadId());
                item.setHeadCode(sourcingVO.getCode());
                item.setCheckDate(sourcingVO.getCheckDate());
                item.setSupplyId(sourcingVO.getSupplyID());
                item.setSupplyName(sourcingVO.getSupplyName());
                SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                if(ObjectUtil.isNotEmpty(sysMaterial)) {
                    item.setMaterialName(materialMap.get(item.getMaterialId()).getMaterialName());
                    item.setMainUnitName(materialMap.get(item.getMaterialId()).getMainUnitKis());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                }
            });
        }
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplyDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplyMap = supplyDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingItemVOS.forEach(item-> {
                if(supplyMap.containsKey(item.getSupplyId())) {
                    item.setSupplyName(supplyMap.get(item.getSupplyId()).getAddress());
                }
            });
        }
        return sourcingItemVOS;
    }

    /**
     * 委外订单详情
     * @return
     */
    @Override
    public List<ErpOutSourcingItemVO> sourcingItem(ErpSourcingPageParam param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", "  and t1.FCheckDate >= '2023-11-01' ");
        paramMap.put("ItemClassId", "1007105");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisOutSourcingHeadVO> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisOutSourcingHeadVO.class)).collect(Collectors.toList());
        List<ErpOutSourcingVO> sourcingVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        List<KisOutSourcingBodyVO> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisOutSourcingBodyVO.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpOutSourcingItemVO> sourcingItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpOutSourcingItemVO::getHeadId).reversed()).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(sourcingVOS) || ObjectUtil.isEmpty(sourcingVOS)){
            return null;
        }
        List<Integer> bomIds = sourcingItemVOS.stream().map(ErpOutSourcingItemVO::getBomID).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(bomIds)){
            List<MesBom> bomDOS = mesBomService.list(new LambdaQueryWrapper<MesBom>().in(MesBom::getId, bomIds));
            Map<Integer, MesBom> bomMap = bomDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingItemVOS.forEach(item-> {
                if(bomMap.containsKey(item.getBomID())) item.setBomName(bomMap.get(item.getBomID()).getBomName());
            });
        }
        List<Integer> supplyIds = sourcingVOS.stream().map(ErpOutSourcingVO::getSupplyID).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplierDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplierMap = supplierDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingVOS.forEach(item-> {
                if(supplierMap.containsKey(item.getSupplyID())) item.setSupplyName(supplierMap.get(item.getSupplyID()).getSupplierName());
            });
        }
        Map<Integer, ErpOutSourcingVO> sourcingVOSMap = sourcingVOS.stream().collect(Collectors.toMap(ErpOutSourcingVO::getId, Iterable -> Iterable, (v1, v2) -> v1));
        List<Integer> materialIds = sourcingItemVOS.stream().map(ErpOutSourcingItemVO::getMaterialId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingItemVOS.forEach(item-> {
                ErpOutSourcingVO sourcingVO = sourcingVOSMap.get(item.getHeadId());
                item.setHeadCode(sourcingVO.getCode());
                item.setCheckDate(sourcingVO.getCheckDate());
                item.setSupplyId(sourcingVO.getSupplyID());
                item.setSupplyName(sourcingVO.getSupplyName());
                SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                if(ObjectUtil.isNotEmpty(sysMaterial)) {
                    item.setMaterialName(materialMap.get(item.getMaterialId()).getMaterialName());
                    item.setMainUnitName(materialMap.get(item.getMaterialId()).getMainUnitKis());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                }
            });
        }
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplyDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplyMap = supplyDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            sourcingItemVOS.forEach(item-> {
                if(supplyMap.containsKey(item.getSupplyId())) {
                    item.setSupplyName(supplyMap.get(item.getSupplyId()).getAddress());
                }
            });
        }
        return sourcingItemVOS;
    }

    /**
     * 委外投料
     * @return
     */
    @Override
    public List<ErpSourcingFeedingVO> sourcingFeeding(ErpSourcingFeedingPageParam param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", "   and t1.FCheckDate >= '2023-11-01'  and t1.ftype=1067");
        paramMap.put("ItemClassId", "88");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisSourcingFeedingHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisSourcingFeedingHeadDto.class)).collect(Collectors.toList());
        List<ErpSourcingFeedingVO> feedingVOS = headVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpSourcingFeedingVO::getId).reversed()).collect(Collectors.toList());


        List<Integer> sourceIds = feedingVOS.stream().map(ErpSourcingFeedingVO::getSourceId).distinct().collect(Collectors.toList());
//        String idsParam = StringUtils.join(sourceIds, ",");
//        paramMap.put("Filter", " and t1.FInterID in (" + idsParam + ")");
//        KisApiResultVOS kisApiResultVOS2 = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
//        String datas2 = kisApiResultVOS2.getDatas();
//        List<KisHeadAndBodyVO> headAndBodyVOS2 = JSON.parseArray(datas2, KisHeadAndBodyVO.class);
//        List<KisOutSourcingHeadVO> headVOS2 = headAndBodyVOS2.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisOutSourcingHeadVO.class)).collect(Collectors.toList());
//        List<ErpOutSourcingVO> sourcingVOS = headVOS2.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
//        Map<Integer, String> sourcingMap = sourcingVOS.stream().collect(Collectors.toMap(ErpOutSourcingVO::getId, ErpOutSourcingVO::getCode));

        //填充委外投料单的编码
        List<ErpOutSourcingItemVO> sourceVos = this.sourcingItem(sourceIds);
        Map<Integer, String> sourceVosMap = sourceVos.stream().collect(Collectors.toMap(item -> item.getHeadId(), item -> item.getHeadCode(), (v1, v2) -> v1));
        log.error("===========sourceIds:{}",sourceIds);
        log.error("===========sourceVos:{}",sourceVos);
        log.error("===========sourceVosMap:{}",sourceVosMap);

        List<Integer> materialIds = feedingVOS.stream().map(ErpSourcingFeedingVO::getMaterialId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            feedingVOS.forEach(item-> {
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMaterialName(sysMaterial.getMaterialName());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                    item.setMainUnitName(sysMaterial.getMainUnitKis());
                }
                if(sourceVosMap.containsKey(item.getSourceId())) {
                    item.setSourceCode(sourceVosMap.get(item.getSourceId()));
                }
            });
        }
        return feedingVOS;
    }

    /**
     * 委外投料详情
     * @return
     */
    @Override
    public List<ErpSourcingFeedingItemVO> sourcingFeedingDetail(List<Integer> ids) {
        String idsParam = StringUtils.join(ids, ",");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", " and  t1.FInterID in (" + idsParam + ")");
        paramMap.put("ItemClassId", "88");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisSourcingFeedingHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisSourcingFeedingHeadDto.class)).collect(Collectors.toList());
        List<ErpSourcingFeedingVO> feedingVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(feedingVOS) || ObjectUtil.isEmpty(feedingVOS)){
            return null;
        }
        ErpSourcingFeedingVO feedingVO = feedingVOS.get(0);
        List<KisSourcingFeedingBodyDto> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisSourcingFeedingBodyDto.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpSourcingFeedingItemVO> feedingItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpSourcingFeedingItemVO::getHeadId).reversed()).collect(Collectors.toList());
        List<Integer> materialIds = feedingItemVOS.stream().map(ErpSourcingFeedingItemVO::getMaterialId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            feedingItemVOS.forEach(item-> {
                item.setCheckDate(feedingVO.getCheckDate());
                item.setHeadCode(feedingVO.getCode());
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMaterialName(sysMaterial.getMaterialName());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                    item.setMainUnitName(sysMaterial.getMainUnitKis());
                }
            });
        }
        //填充委外投料单的编码
        List<Integer> sourceIds = feedingItemVOS.stream().map(ErpSourcingFeedingItemVO::getSourceId).collect(Collectors.toList());
        List<ErpOutSourcingItemVO> sourceVos = this.sourcingItem(sourceIds);
        Map<Integer, String> sourceVosMap = sourceVos.stream().collect(Collectors.toMap(item -> item.getHeadId(), item -> item.getHeadCode(), (v1, v2) -> v1));

        List<Integer> bomIds = feedingItemVOS.stream().map(ErpSourcingFeedingItemVO::getBomId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(bomIds)){
            List<MesBom> bomDOS = mesBomService.list(new LambdaQueryWrapper<MesBom>().in(MesBom::getId, bomIds));
            Map<Integer, MesBom> bomMap = bomDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            feedingItemVOS.forEach(item-> {
                if(bomMap.containsKey(item.getBomId())) {
                    item.setBomName(bomMap.get(item.getBomId()).getBomName());
                    item.setBomCode(bomMap.get(item.getBomId()).getBomNo());
                }
                if(sourceVosMap.containsKey(item.getSourceId())) {
                    item.setSourceCode(sourceVosMap.get(item.getSourceId()));
                }
            });
        }



        return feedingItemVOS;
    }

    @Override
    public List<ErpPurchaseVO> purchase(ErpPurchasePageParam param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", "   and t1.fdate>='2023-11-01' and t1.FCheckerID is not null  ");
        paramMap.put("ItemClassId", "71");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisPurchaseHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisPurchaseHeadDto.class)).collect(Collectors.toList());
        List<ErpPurchaseVO> purchaseVOS = headVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpPurchaseVO::getId).reversed()).collect(Collectors.toList());
        List<Integer> supplyIds = purchaseVOS.stream().map(ErpPurchaseVO::getSupplyId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplierDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplierMap = supplierDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            purchaseVOS.forEach(item-> {
                if(supplierMap.containsKey(item.getSupplyId())) item.setSupplyName(supplierMap.get(item.getSupplyId()).getSupplierName());
            });
        }
        List<Integer> userIds = purchaseVOS.stream().map(ErpPurchaseVO::getEmpId).collect(Collectors.toList());
        List<Integer> checkerIds = purchaseVOS.stream().map(ErpPurchaseVO::getCheckerId).collect(Collectors.toList());
        List<Integer> billerIds = purchaseVOS.stream().map(ErpPurchaseVO::getBillerId).collect(Collectors.toList());
        List<Integer> mangerIds = purchaseVOS.stream().map(ErpPurchaseVO::getMangerId).collect(Collectors.toList());
        userIds.addAll(checkerIds);
        userIds.addAll(billerIds);
        userIds.addAll(mangerIds);
        if (ObjectUtil.isNotEmpty(userIds)){
            List<SysUser> sysUserDOS = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userIds).or().in(SysUser::getClerkId, userIds));
            Map<Integer, SysUser> sysUserMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            Map<Integer, SysUser> sysClerkMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getClerkId(), Iterable -> Iterable, (v1, v2) -> v1));
            purchaseVOS.forEach(item-> {
                if(sysUserMap.containsKey(item.getEmpId())) item.setEmpName(sysUserMap.get(item.getEmpId()).getRealName());
                if(sysClerkMap.containsKey(item.getCheckerId())) item.setCheckerName(sysClerkMap.get(item.getCheckerId()).getRealName());
                if(sysClerkMap.containsKey(item.getBillerId())) item.setBillerName(sysClerkMap.get(item.getBillerId()).getRealName());
                if(sysUserMap.containsKey(item.getMangerId())) item.setMangerName(sysUserMap.get(item.getMangerId()).getRealName());
            });
        }
        return purchaseVOS;
    }

    @Override
    public List<ErpPurchaseDetailVO> purchaseDetail(List<Integer> ids) {HashMap<String, Object> paramMap = new HashMap<>();
        String idsParam = StringUtils.join(ids, ",");
        paramMap.put("Filter", "    and  t1.FInterID in (" + idsParam + ")");
        paramMap.put("ItemClassId", "71");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisPurchaseHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisPurchaseHeadDto.class)).collect(Collectors.toList());
        List<ErpPurchaseVO> purchaseVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        List<KisPurchaseBodyDto> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisPurchaseBodyDto.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpPurchaseDetailVO> purchaseItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpPurchaseDetailVO::getHeadId).reversed()).collect(Collectors.toList());

        List<Integer> supplyIds = purchaseVOS.stream().map(ErpPurchaseVO::getSupplyId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplierDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplierMap = supplierDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            purchaseVOS.forEach(item-> {
                if(supplierMap.containsKey(item.getSupplyId())) item.setSupplyName(supplierMap.get(item.getSupplyId()).getSupplierName());
            });
        }
        List<Integer> userIds = purchaseVOS.stream().map(ErpPurchaseVO::getEmpId).collect(Collectors.toList());
        List<Integer> checkerIds = purchaseVOS.stream().map(ErpPurchaseVO::getCheckerId).collect(Collectors.toList());
        List<Integer> billerIds = purchaseVOS.stream().map(ErpPurchaseVO::getBillerId).collect(Collectors.toList());
        List<Integer> mangerIds = purchaseVOS.stream().map(ErpPurchaseVO::getMangerId).collect(Collectors.toList());
        userIds.addAll(checkerIds);
        userIds.addAll(billerIds);
        userIds.addAll(mangerIds);
        if (ObjectUtil.isNotEmpty(userIds)){
            List<SysUser> sysUserDOS = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userIds).or().in(SysUser::getClerkId, userIds));
            Map<Integer, SysUser> sysUserMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            Map<Integer, SysUser> sysClerkMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getClerkId(), Iterable -> Iterable, (v1, v2) -> v1));
            purchaseVOS.forEach(item-> {
                if(sysClerkMap.containsKey(item.getCheckerId())) item.setCheckerName(sysClerkMap.get(item.getCheckerId()).getRealName());
            });
        }

        Map<Integer, ErpPurchaseVO> purchaseVOSMap = purchaseVOS.stream().collect(Collectors.toMap(ErpPurchaseVO::getId, Iterable -> Iterable, (v1, v2) -> v1));
        List<Integer> materialIds = purchaseItemVOS.stream().map(ErpPurchaseDetailVO::getMaterialId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            purchaseItemVOS.forEach(item-> {
                ErpPurchaseVO purchaseVO = purchaseVOSMap.get(item.getHeadId());
                item.setHeadCode(purchaseVO.getCode());
                item.setCheckerName(purchaseVO.getCheckerName());
                item.setSupplyName(purchaseVO.getSupplyName());
                item.setSupplyId(purchaseVO.getSupplyId());
                item.setCheckDate(purchaseVO.getCheckDate());
                item.setHeadCode(purchaseVO.getCode());
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMaterialName(sysMaterial.getMaterialName());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                    item.setMainUnitName(sysMaterial.getMainUnitKis());
                }
            });
        }
        return purchaseItemVOS;
    }

    @Override
    public List<ErpPurchaseNoticeVO> purchaseNoticeSync(ErpPurchaseNoticePageParam scmPurchasePageParam) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", "   and t1.fcheckdate>='2023-11-01' ");
        paramMap.put("ItemClassId", "72");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisPurchaseNoticeHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisPurchaseNoticeHeadDto.class)).collect(Collectors.toList());
        List<ErpPurchaseNoticeVO> noticeVOS = headVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpPurchaseNoticeVO::getId).reversed()).collect(Collectors.toList());

        List<Integer> userIds = noticeVOS.stream().map(ErpPurchaseNoticeVO::getCreateId).collect(Collectors.toList());
        List<Integer> auditorIds = noticeVOS.stream().map(ErpPurchaseNoticeVO::getAuditorId).collect(Collectors.toList());
        List<Integer> buyerIds = noticeVOS.stream().map(ErpPurchaseNoticeVO::getBuyerId).collect(Collectors.toList());
        List<Integer> managerIds = noticeVOS.stream().map(ErpPurchaseNoticeVO::getManagerId).collect(Collectors.toList());
        userIds.addAll(auditorIds);
        userIds.addAll(buyerIds);
        userIds.addAll(managerIds);
        if (ObjectUtil.isNotEmpty(userIds)){
            List<SysUser> sysUserDOS = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userIds).or().in(SysUser::getClerkId, userIds));
            Map<Integer, SysUser> sysUserMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            Map<Integer, SysUser> sysClerkMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getClerkId(), Iterable -> Iterable, (v1, v2) -> v1));
            noticeVOS.forEach(item-> {
                if(sysUserMap.containsKey(item.getCreateId())) item.setCreateName(sysUserMap.get(item.getCreateId()).getRealName());
                if(sysClerkMap.containsKey(item.getAuditorId())) item.setAuditorName(sysClerkMap.get(item.getAuditorId()).getRealName());
                if(sysUserMap.containsKey(item.getBuyerId())) item.setBuyerName(sysUserMap.get(item.getBuyerId()).getRealName());
                if(sysUserMap.containsKey(item.getManagerId())) item.setManagerName(sysUserMap.get(item.getManagerId()).getRealName());
            });
        }
        List<Integer> supplyIds = noticeVOS.stream().map(ErpPurchaseNoticeVO::getSupplyID).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplierDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplierMap = supplierDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            noticeVOS.forEach(item-> {
                if(supplierMap.containsKey(item.getSupplyID())) item.setSupplyName(supplierMap.get(item.getSupplyID()).getSupplierName());
            });
        }
        return noticeVOS;
    }

    @Override
    public List<ErpPurchaseNoticeItemVO> purchaseNoticeDetailSync(List<Integer> ids) {
        HashMap<String, Object> paramMap = new HashMap<>();
        String idsParam = StringUtils.join(ids, ",");
        paramMap.put("Filter", "   and  t1.FInterID in (" + idsParam + ")");
        paramMap.put("ItemClassId", "72");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisPurchaseNoticeHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisPurchaseNoticeHeadDto.class)).collect(Collectors.toList());
        List<ErpPurchaseNoticeVO> noticeVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        List<KisPurchaseNoticeBodyDto> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisPurchaseNoticeBodyDto.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpPurchaseNoticeItemVO> noticeItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpPurchaseNoticeItemVO::getHeadId).reversed()).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(noticeVOS) || ObjectUtil.isEmpty(noticeVOS)){
            return null;
        }
        ErpPurchaseNoticeVO noticeVO = noticeVOS.get(0);
        List<Integer> materialIds = noticeItemVOS.stream().map(ErpPurchaseNoticeItemVO::getMaterialId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            noticeItemVOS.forEach(item-> {
                item.setHeadCode(noticeVO.getCode());
                item.setAuditorId(noticeVO.getAuditorId());
                item.setCheckDate(noticeVO.getCheckDate());
                item.setHeadCode(noticeVO.getCode());
                item.setSupplyID(noticeVO.getSupplyID());
                item.setSupplyName(noticeVO.getSupplyName());
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMaterialName(sysMaterial.getMaterialName());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                    item.setMainUnitName(sysMaterial.getMainUnitKis());
                }
            });
        }
        return noticeItemVOS;
    }

    @Override
    public List<ErpPurchaseNoticeItemVO> purchaseNoticeDetailSync(ErpPurchaseNoticePageParam param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", "   and t1.fcheckdate>='2023-11-01' ");
        paramMap.put("ItemClassId", "72");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisPurchaseNoticeHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisPurchaseNoticeHeadDto.class)).collect(Collectors.toList());
        List<ErpPurchaseNoticeVO> noticeVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        List<KisPurchaseNoticeBodyDto> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisPurchaseNoticeBodyDto.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpPurchaseNoticeItemVO> noticeItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpPurchaseNoticeItemVO::getHeadId).reversed()).collect(Collectors.toList());
        if (ObjectUtil.isEmpty(noticeVOS) || ObjectUtil.isEmpty(noticeVOS)){
            return null;
        }
        Map<Integer, ErpPurchaseNoticeVO> noticeVOSMap = noticeVOS.stream().collect(Collectors.toMap(ErpPurchaseNoticeVO::getId, Iterable -> Iterable, (v1, v2) -> v1));
        List<Integer> materialIds = noticeItemVOS.stream().map(ErpPurchaseNoticeItemVO::getMaterialId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            noticeItemVOS.forEach(item-> {
                ErpPurchaseNoticeVO noticeVO = noticeVOSMap.get(item.getHeadId());
                item.setHeadCode(noticeVO.getCode());
                item.setAuditorId(noticeVO.getAuditorId());
                item.setCheckDate(noticeVO.getCheckDate());
                item.setHeadCode(noticeVO.getCode());
                item.setSupplyID(noticeVO.getSupplyID());
                item.setSupplyName(noticeVO.getSupplyName());
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMaterialName(sysMaterial.getMaterialName());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                    item.setMainUnitName(sysMaterial.getMainUnitKis());
                }
            });
        }
        return noticeItemVOS;
    }

    @Override
    public IPage<ScmSaleNoticeListVo> saleNoticeSync(ScmSaleNoticeParam param) {
        return null;
    }

    @Override
    public ScmSaleNoticeVo saleNoticeDetailSync(Integer id) {
        return null;
    }

    @Override
    public List<ErpSaleVO> saleSync(ErpSalePageParam param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", " and t1.fcheckdate>='2023-11-01' ");
        paramMap.put("ItemClassId", "81");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisSaleHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisSaleHeadDto.class)).collect(Collectors.toList());
        List<ErpSaleVO> saleVOS = headVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpSaleVO::getId).reversed()).collect(Collectors.toList());

        List<Integer> supplyIds = saleVOS.stream().map(ErpSaleVO::getCustId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplierDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplierMap = supplierDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            saleVOS.forEach(item-> {
                if(supplierMap.containsKey(item.getCustId())) item.setCustName(supplierMap.get(item.getCustId()).getSupplierName());
            });
        }
        List<Integer> userIds = saleVOS.stream().map(ErpSaleVO::getEmpId).collect(Collectors.toList());
        List<Integer> auditorIds = saleVOS.stream().map(ErpSaleVO::getAuditorId).collect(Collectors.toList());
        List<Integer> createIds = saleVOS.stream().map(ErpSaleVO::getCreateId).collect(Collectors.toList());
        List<Integer> sManagerIds = saleVOS.stream().map(ErpSaleVO::getManagerId).collect(Collectors.toList());
        userIds.addAll(auditorIds);
        userIds.addAll(createIds);
        userIds.addAll(sManagerIds);
        if (ObjectUtil.isNotEmpty(userIds)){
            List<SysUser> sysUserDOS = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userIds).or().in(SysUser::getClerkId, userIds));
            Map<Integer, SysUser> sysUserMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            Map<Integer, SysUser> sysClerkMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getClerkId(), Iterable -> Iterable, (v1, v2) -> v1));
            saleVOS.forEach(item-> {
                if(sysUserMap.containsKey(item.getEmpId())) item.setEmpName(sysUserMap.get(item.getEmpId()).getRealName());
                if(sysClerkMap.containsKey(item.getAuditorId())) item.setAuditorName(sysClerkMap.get(item.getAuditorId()).getRealName());
                if(sysClerkMap.containsKey(item.getCreateId())) item.setCreateName(sysClerkMap.get(item.getCreateId()).getRealName());
                if(sysUserMap.containsKey(item.getManagerId())) item.setManagerName(sysUserMap.get(item.getManagerId()).getRealName());
            });
        }
        return saleVOS;
    }

    @Override
    public List<ErpSaleDetailVO> saleDetailSync(List<Integer> ids) {
        HashMap<String, Object> paramMap = new HashMap<>();
        String idsParam = StringUtils.join(ids, ",");
        paramMap.put("Filter", "  and  t1.FInterID in (" + idsParam + ")");
        paramMap.put("ItemClassId", "81");
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/BillData", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisHeadAndBodyVO> headAndBodyVOS = JSON.parseArray(datas, KisHeadAndBodyVO.class);
        List<KisSaleHeadDto> headVOS = headAndBodyVOS.stream().map(item -> JSON.parseObject(JSON.parse(item.getBillHead()).toString(), KisSaleHeadDto.class)).collect(Collectors.toList());
        List<ErpSaleVO> saleVOS = headVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());

        List<KisSaleBodyDto> bodyVOS = headAndBodyVOS.stream().map(item -> JSON.parseArray(JSON.parse(item.getBillEntry()).toString(), KisSaleBodyDto.class)).flatMap(item -> item.stream()).collect(Collectors.toList());
        List<ErpSaleDetailVO> saleItemVOS = bodyVOS.stream().map(item -> item.voToPo(item))
                .sorted(Comparator.comparing(ErpSaleDetailVO::getHeadId).reversed()).collect(Collectors.toList());

        Map<Integer, ErpSaleVO> saleVOSMap = saleVOS.stream().collect(Collectors.toMap(ErpSaleVO::getId, Iterable -> Iterable, (v1, v2) -> v1));

        List<Integer> auditorIds = saleVOS.stream().map(ErpSaleVO::getAuditorId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(auditorIds)){
            List<SysUser> sysUserDOS = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, auditorIds));
            Map<Integer, SysUser> sysUserMap = sysUserDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            saleVOS.forEach(item-> {
                if(sysUserMap.containsKey(item.getAuditorId())) item.setAuditorName(sysUserMap.get(item.getAuditorId()).getRealName());
            });
        }
        List<Integer> supplyIds = saleVOS.stream().map(ErpSaleVO::getCustId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(supplyIds)){
            List<SysSupplier> supplierDOS = sysSupplierService.list(new LambdaQueryWrapper<SysSupplier>().in(SysSupplier::getId, supplyIds));
            Map<Integer, SysSupplier> supplierMap = supplierDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            saleVOS.forEach(item-> {
                if(supplierMap.containsKey(item.getCustId())) item.setCustName(supplierMap.get(item.getCustId()).getSupplierName());
            });
        }
        List<Integer> materialIds = saleItemVOS.stream().map(ErpSaleDetailVO::getMaterialId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            saleItemVOS.forEach(item-> {
                ErpSaleVO saleVO = saleVOSMap.get(item.getHeadId());
                item.setCheckDate(saleVO.getCheckDate());
                item.setCheckerName(saleVO.getAuditorName());
                item.setDeptID(saleVO.getDeptID());
                item.setCustId(saleVO.getCustId());
                item.setCustName(saleVO.getCustName());
                item.setHeadCode(saleVO.getCode());
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMaterialName(sysMaterial.getMaterialName());
                    item.setMaterialNo(sysMaterial.getMaterialNo());
                    item.setMaterialSpecific(sysMaterial.getMaterialSpecific());
                    item.setMainUnitName(sysMaterial.getMainUnitKis());
                }
            });
        }
        return saleItemVOS;
    }

    @Override
    public List<ErpStocktakingVO> stocktakingList(ErpSalePageParam param) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Acct", "XRTEST");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/GetProcessId", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisStocktakingDto> stocktakingDtO = JSON.parseArray(datas, KisStocktakingDto.class);
        List<ErpStocktakingVO> stocktakingVO = stocktakingDtO.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        return stocktakingVO;
    }

    @Override
    public List<ErpStocktakingDetailVO> stocktakingDetail(Integer id) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("InterId", id);
        paramMap.put("Acct", "XRTEST");
        paramMap.put("pageNo", "1");
        paramMap.put("pagesize", "100");
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/GetProcessList", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisStocktakingDetailDto> stocktakingDetailDtos = JSON.parseArray(datas, KisStocktakingDetailDto.class);
        List<ErpStocktakingDetailVO> stocktakingDetailVO = stocktakingDetailDtos.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());
        return stocktakingDetailVO;
    }


    /**
     * 实时库存
     * @return
     */
    @Override
    public IPage<ErpRealTimeDto> realtimeInventory(ErpRealTimePageParam param) {
        StringBuilder filter = new StringBuilder("");
        if (!ObjectUtils.isEmpty(param.getMaterialId())) filter.append(" and 物料ID= ").append(param.getMaterialId());
        if (!ObjectUtils.isEmpty(param.getMaterialIds())) filter.append(" and 物料ID in ").append(param.getMaterialIds());
        if (!ObjectUtils.isEmpty(param.getMaterialName())) filter.append(" and 物料名称= '").append(param.getMaterialName()).append("'");
        if (!ObjectUtils.isEmpty(param.getStockId())) filter.append(" and 仓库ID= ").append(param.getStockId());
        if (!ObjectUtils.isEmpty(param.getStockName())) filter.append(" and 仓库名称= '").append(param.getStockName()).append("'");
        if (!ObjectUtils.isEmpty(param.getStockLocationId())) filter.append(" and 仓位ID= ").append(param.getStockLocationId());
        if (!ObjectUtils.isEmpty(param.getStockLocationName())) filter.append(" and 仓位名称= '").append(param.getStockLocationName()).append("'");
        if (!ObjectUtils.isEmpty(param.getBatch())) filter.append(" and 批号= '").append(param.getBatch()).append("'");
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Filter", filter.toString());
        paramMap.put("Acct", "XRTEST");
        paramMap.put("pageSize", param.getPageSize());
        paramMap.put("pageNo", param.getCurrentPage());

//        log.error("实时库存查询参数：{}"+ JSON.toJSONString(paramMap)); //需要及时关闭，有个定时任务的参数过多
        KisApiRealTimeResultVOS kisApiResultVOS = postRealTimeRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/Inventory", paramMap);
        String datas = kisApiResultVOS.getDatas();
        List<KisRealTimeDto> realTimeVOS = JSON.parseArray(datas, KisRealTimeDto.class);
        List<ErpRealTimeDto> realTimeDtos = realTimeVOS.stream().map(item -> item.voToPo(item)).collect(Collectors.toList());



        List<Integer> materialIds = realTimeDtos.stream().map(ErpRealTimeDto::getMaterialId).distinct().collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(materialIds)){
            List<SysMaterial> materialDOS = sysMaterialService.list(new LambdaQueryWrapper<SysMaterial>().in(SysMaterial::getId, materialIds));
            Map<Integer, SysMaterial> materialMap = materialDOS.stream().collect(Collectors.toMap(item -> item.getId(), Iterable -> Iterable, (v1, v2) -> v1));
            realTimeDtos.forEach(item-> {
                if(materialMap.containsKey(item.getMaterialId())) {
                    SysMaterial sysMaterial = materialMap.get(item.getMaterialId());
                    item.setMainUnitName(sysMaterial.getMainUnitKis());
                }
            });
        }
        Page<ErpRealTimeDto> page = new Page<ErpRealTimeDto>(param.getCurrentPage(), param.getPageSize());
        page.setRecords(realTimeDtos);
        page.setTotal(kisApiResultVOS.getRecords());
        return page;
    }

    public KisApiResultVOS postRequest(String url, HashMap<String, Object> paramMap) {
        String result = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json; charset=utf-8")// 头信息，多个头信息多次调用此方法即可
                .header(Header.ACCEPT, "application/json")// 头信息，多个头信息多次调用此方法即可
                // .form(paramMap)//表单内容
                .body(JSON.toJSONString(paramMap))
                .timeout(20000)// 超时，毫秒
                .execute().body();
        KisApiResultVOS apiResultVOS = JSON.parseObject(JSON.parseObject(result, String.class), KisApiResultVOS.class);
        // 0 为正常  1 异常
        if (ObjectUtil.isEmpty(apiResultVOS.getStatus()) || !apiResultVOS.getStatus().equals(0)) {
            log.info("---返回数据：" + JSON.toJSONString(result));
            throw new BDException("同步失败，请联系管理员！");
        }
        return apiResultVOS;
    }

    public KisApiRealTimeResultVOS postRealTimeRequest(String url, HashMap<String, Object> paramMap) {
        String result = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json; charset=utf-8")// 头信息，多个头信息多次调用此方法即可
                .header(Header.ACCEPT, "application/json")// 头信息，多个头信息多次调用此方法即可
                // .form(paramMap)//表单内容
                .body(JSON.toJSONString(paramMap))
                .timeout(20000)// 超时，毫秒
                .execute().body();
        KisApiRealTimeResultVOS apiResultVOS = JSON.parseObject(JSON.parseObject(result, String.class), KisApiRealTimeResultVOS.class);
        // 0 为正常  1 异常
        if (ObjectUtil.isEmpty(apiResultVOS.getStatus()) || !apiResultVOS.getStatus().equals(0)) {
            log.info("---返回数据：" + JSON.toJSONString(result));
            throw new BDException("同步失败，请联系管理员！");
        }
        return apiResultVOS;
    }
}
